<template>
  <h2>简单监听</h2>
  <div>age: {{ age }}</div>
  <button @click="age++">age++</button>
  <hr />
  <h2>多个ref 值监听</h2>
  <div>name: {{ name }}</div>
  <button @click="name += '》'">name change</button>
  <div>gender: {{ gender }}</div>
  <button @click="gender += '--'">gender change</button>
  <hr />
  <h2>reactive响应式对象监听</h2>
  <div>age: {{ info.age }}</div>
  <div>name: {{ info.name }}</div>
  <div>gender: {{ info.gender }}</div>
  <div>salary: {{ info.job.salary }} k</div>
  <button @click="info.age++">age++</button>
  <button @click="info.name += '》'">name change</button>
  <button @click="info.gender += '--'">gender change</button>
  <button @click="info.job.salary++">salary change</button>
</template>

<script>
import { reactive, ref, setup, watch } from "vue";

export default {
  setup() {
    let age = ref(18);
    let name = ref("mal");
    let gender = ref("male");
    const info = reactive({
      name: "mal",
      age: 18,
      gender: "male",
      job: {
        salary: 20,
      },
    });

    // 单个ref 值监听
    watch(
      age,
      (newValue, oldValue) => {
        console.log("age变化了", newValue, oldValue);
      },
      { immediate: true }
    );

    // 多个ref 值监听
    watch([name, gender], (newValue, oldValue) => {
      console.log("合并监听值变化了", newValue, oldValue);
    });

    // 响应式对象监听
    watch(info, (newValue, oldValue) => {
      console.log("响应式对象变化了", newValue, oldValue);
    });

    // 对象属性监听
    watch(
      () => info.age,
      (newValue, oldValue) => {
        console.log("info.age属性发生了变化", newValue, oldValue);
      }
    );
    watch([() => info.name, () => info.gender], (newValue, oldValue) => {
      console.log("info属性合并监听", newValue, oldValue);
    });
    watch(
      () => info.job,
      (newValue, oldValue) => {
        console.log("info.job属性发生了变化", newValue, oldValue);
      },
      { deep: true }
    );

    return {
      age,
      name,
      gender,
      info,
    };
  },
};
</script>
